#include "praxis/services/global_config_manager.h"

#include <fstream>

namespace praxis {
struct CGlobalConfigManager::Impl {
  const std::string config_filename_ = "system_config.json";
  json schema_;
  json data_;

  explicit Impl(const json& schema) : schema_(schema) {
    Load();
    ApplyDefaults();
  }

  void Load() {
    std::ifstream f(config_filename_);
    if (f.is_open()) {
      try {
        data_ = json::parse(f);
      } catch (...) {
        // File is corrupt or empty, will be handled by ApplyDefaults
      }
    }
  }

  void ApplyDefaults() {
    if (schema_.contains("properties")) {
      for (auto it = schema_["properties"].begin();
           it != schema_["properties"].end(); ++it) {
        if (!data_.contains(it.key())) {
          data_[it.key()] = it.value().value("default", json());
        }
      }
    }
  }

  bool Save() {
    std::ofstream f(config_filename_);
    if (!f.is_open()) return false;
    f << data_.dump(4);  // Pretty print
    return true;
  }
};

CGlobalConfigManager::CGlobalConfigManager(const json& schema)
    : impl_(std::make_unique<Impl>(schema)) {}

CGlobalConfigManager::~CGlobalConfigManager() = default;

bool CGlobalConfigManager::Save() { return impl_->Save(); }

json& CGlobalConfigManager::GetData() { return impl_->data_; }
}  // namespace praxis